<template>
  <div>
    <el-form ref="formData" :model="formData" :rules="rules" label-width="100px">


      <el-form-item label="楼栋" prop="buildingId">
        <el-select v-model="formData.buildingId" placeholder="请选择">
          <el-option v-for="item in buildingList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="单元名称" prop="unitId">
        <el-select v-model="formData.unitId" placeholder="请选择">
          <el-option v-for="item in unitList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="宿舍名称" prop="dormitoryId">
        <el-select v-model="formData.dormitoryId" placeholder="请选择">
          <el-option v-for="item in dormitoryList" :key="item.value" :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="学生姓名" prop="userId">
        <el-select v-model="formData.userId" placeholder="请选择">
          <el-option v-for="item in studentList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateForm()">提 交</el-button>
        <el-button type="info" @click="cancellation()">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    message: {
      type: String,
      default: 'Default Message' // 设置 message 的默认值为 'Default Message'
    }
  },
  data() {
    return {
      formData: {
        assignmentId: '',
        buildingId: '',
        unitId: '',
        dormitoryId: '',
        userId: '',
        remark: ''
      },
      rules: {
        buildingId: [
          {required: true, message: '请选择楼栋名称', trigger: 'change'}
        ],
        unitId: [
          {required: true, message: '请选择单元名称', trigger: 'change'}
        ],
        dormitoryId: [
          {required: true, message: '请选择宿舍名称', trigger: 'change'}
        ],
        userId: [
          {required: true, message: '请选择学生姓名', trigger: 'change'}
        ]
      },
      buildingList: [ /* 从后端获取楼栋列表数据 */],
      unitList: [ /* 从后端获取单元列表数据 */],
      dormitoryList: [ /* 从后端获取宿舍列表数据 */],
      studentList: [ /* 从后端获取学生列表数据 */],

    };
  },
  watch: {
    // 监听 message 属性的变化
    message(newValue, oldValue) {
      this.getDormitoryAllocationById(newValue);
    },
    // 监听 editedDormitoriesForm.buildingId 属性的变化
    'formData.buildingId': function (newBuildingId, oldBuildingId) {
      // 执行您的逻辑代码
      this.formData.unitId = "";
      this.queryUnitInformation()
      // 查询学生信息
      this.formData.userId = "";
      this.queryStudentInformation();
    },
    // 监听 editedDormitoriesForm.unitId 属性的变化
    'formData.unitId': function (newUnitId, oldUnitId) {
      // 执行您的逻辑代码
      this.formData.dormitoryId = "";
      this.queryDormitoryInformation()
    },

  },
  mounted() {
    // 根据ID查询宿舍分配信息
    this.getDormitoryAllocationById(this.message);
    //   查询楼栋信息
    this.queryBuildingInformation();
    //   查询单元
    this.queryUnitInformation();
    //   查询宿舍
    this.queryDormitoryInformation();
    // 查询学生信息
    this.queryStudentInformation();
  },
  methods: {
    // 根据ID查询宿舍分配信息
    getDormitoryAllocationById(assignmentId) {
      // 调用后端接口获取数据
      this.$axios.post('/api/studentDormAssignments/getStudentDormAssignments', {
        assignmentId: assignmentId,
      }, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        // 请求成功后更新表格数据和分页信息
        if (response.data.code === 200) {
          this.formData = response.data.data;
          this.total = response.data.data.total;
          this.succeed("查询成功");
        } else {
          this.$message.error(response.data.msg || '查询学生宿舍关系表失败');
        }
      }).catch(error => {
        // 错误处理
        this.$message.error(error || '查询学生宿舍关系表失败');
      });
    },

    // 查询楼栋信息
    queryBuildingInformation() {
      // 调用后端接口获取数据
      this.$axios.post('/api/buildings/list', {}, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        if (response.data.code === 200) {
          this.buildingList = response.data.data.reduce((arr, building) => {
            arr.push({value: building.buildingId, label: building.buildingName});
            return arr;
          }, []);
        } else {
          this.$message.error(response.data.msg || '查询楼栋信息失败');
        }
      }).catch(error => {
        this.$message.error(error || '查询楼栋信息失败');
      });
    },
    // 查询单元信息
    queryUnitInformation() {
      this.unitList = [];
      this.$axios.post('/api/units/list', {
        buildingId: this.formData.buildingId
      }, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        if (response.data.code === 200) {
          if (response.data.data != null && response.data.data.length > 0) {
            this.unitList = response.data.data.reduce((arr, unit) => {
              arr.push({value: unit.unitId, label: unit.unitCode});
              return arr;
            }, []);
          }

        } else {
          this.$message.error(response.data.msg || '查询单元信息失败');
        }
      }).catch(error => {
        this.$message.error(error || '查询单元信息失败');
      });
    },
    // 查询宿舍信息
    queryDormitoryInformation() {
      this.unitList = [];
      this.$axios.post('/api/dormitories/list', {
        dormitoryId: this.formData.dormitoryId
      }, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        if (response.data.code === 200) {
          if (response.data.data != null && response.data.data.length > 0) {
            this.dormitoryList = response.data.data.reduce((arr, dormitory) => {
              arr.push({value: dormitory.dormitoryId, label: dormitory.roomNumber});
              return arr;
            }, []);
          }

        } else {
          this.$message.error(response.data.msg || '查询宿舍信息失败');
        }
      }).catch(error => {
        this.$message.error(error || '查询宿舍信息失败');
      });
    },
    // 查询学生信息
    queryStudentInformation() {
      this.studentList = [];
      this.$axios.get('/api/studentDormAssignments/getStudentsWithoutDormitory/' + this.formData.buildingId, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        if (response.data.code === 200) {
          if (response.data.data != null && response.data.data.length > 0) {
            this.studentList = response.data.data.reduce((arr, student) => {
              arr.push({value: student.userId, label: student.name});
              return arr;
            }, []);
          }
        } else {
          this.$message.error(response.data.msg || '查询学生信息失败');
        }
      }).catch(error => {
        this.$message.error(error || '查询学生信息失败');
      });
    },
    updateForm() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          // 构建宿舍信息对象
          const requestBody = {
            assignmentId: this.formData.assignmentId,
            buildingId: this.formData.buildingId,
            unitId: this.formData.unitId,
            dormitoryId: this.formData.dormitoryId,
            studentId: this.formData.userId,
            remark: this.formData.remark
          };
          this.$axios.post('/api/studentDormAssignments/update', requestBody, {
            headers: {
              'token': this.$store.getters.getToken
            }
          })
              .then(response => {
                this.resetForm();
                // 自定义一个事件，使其能够修改成功之后自动隐藏！
                this.$emit('UpdateDormitoryAllocation');
                // 处理登录成功的情况，比如保存用户信息到本地存储或者跳转到其他页面
                if (response.data.code === 200) {
                  this.$message({
                    message: '添加成功',
                    type: 'success'
                  });
                } else {
                  this.$message.error(response.data.msg || '分配宿舍失败');
                }
              })
              .catch(error => {
                this.resetForm();
                // 自定义一个事件，使其能够添加成功之后自动隐藏！
                this.$emit('UpdateDormitoryAllocation');
                // 处理错误情况
                this.$message({
                  message: '添加失败',
                  type: 'error'
                });
              });
        } else {
          return false;
        }
      });
    },
    resetForm() {
      this.formData.buildingId = '';
      this.formData.unitId = '';
      this.formData.dormitoryId = '';
      this.formData.userId = '';
      this.formData.remark = '';
    },
    // 取消按钮
    cancellation() {
      this.$emit('UpdateDormitoryAllocation');
    },
  }
};
</script>
